//
//  AyOAuthController.m
//  xWeibo
//
//  Created by alvis mac on 8/6/15.
//  Copyright (c) 2015 alvis. All rights reserved.
//

#import "AyOAuthController.h"
#import "MBProgressHUD+MJ.h"
#import "AFNetworking.h"
#import "AyAccount.h"
#import "AyAccountTool.h"
#import "AyWeiboTool.h"
#import "AyDefine.h"
@interface AyOAuthController ()<UIWebViewDelegate>

@end

@implementation AyOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    NSURL *url = [NSURL URLWithString:AyLoginURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 1.请求的URL路径: http://ios.itcast.cn/?code=0f189b682cd020e79303dbb043d4fb28
    NSString *urlStr = request.URL.absoluteString;
    NSRange range = [urlStr rangeOfString:@"code="];
    if (range.length) {
        int loc=range.location+range.length;
        NSString *code=[urlStr substringFromIndex:loc];
        [self accessTokenWithCode:code];
        return NO;
    }
    return YES;
}

- (void)accessTokenWithCode:(NSString *)code
{
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] =AyAppKey;
    params[@"client_secret"] = AyAppSecret;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = AyRedirectURI;
   
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          AyAccount *account=[AyAccount accountWithDict:responseObject];
          [AyAccountTool saveAccount:account];
          [AyWeiboTool chooseRootController];
          [MBProgressHUD hideHUD];
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [MBProgressHUD hideHUD];
      }];

}





- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"正在帮你加载中..."];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{

    [MBProgressHUD hideHUD];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [MBProgressHUD hideHUD];
}


@end
